import re


class Solution:
    def calculate(self, s: str) -> int:
        s = re.sub(" ", "", s)
        s = re.sub(r"\((\d*)\)", r"\1", s)
        while "(" in s:
            mid_s = re.search(r"\(([0-9+-]*?)\)", s)
            mid_num = str(eval(mid_s.group(1)))
            s = re.sub(r"\(([0-9+-]*?)\)", mid_num, s, 1)
        return eval(s)


class Solution2:
    def calculate(self, s: str) -> int:
        s = re.sub(r"\((\d*)\)", r"\1", s)
        mid_list = []
        for one_word in s:
            if one_word == " ":
                continue
            elif one_word == ")":
                mid_s = ""
                while mid_list[-1] != "(":
                    mid_s = mid_list.pop(-1) + mid_s
                mid_list.pop(-1)
                mid_list.append(str(eval(mid_s)))
            else:
                mid_list.append(one_word)
        else:
            mid_s = ""
            while mid_list:
                mid_s = mid_list.pop(-1) + mid_s
            return eval(mid_s)


a = Solution2()
print(a.calculate("1 + (1+1)"))  # 3
print(a.calculate("(1+(4+5+2)-3)+(6+8)"))  # 23
